//
//  requestData.m
//  jiulongLJ
//
//  Created by MyMac on 15/4/2.
//  Copyright (c) 2015年 MyMac. All rights reserved.
//

#import "requestData.h"
#import "XMLDictionary.h"
#import "AFNetworking.h"
#import "Reachability.h"
#import "SaveCachesTool.h"
#import "NSString+Hashing.h"

@implementation RequestData
{
    NSMutableData*dataArray;
    NSURLConnection*_connection;
    DownloadFinishedBlock _finishedBlock;
    DownloadFailedBlock _failedBlock;
   AFHTTPRequestOperationManager *_manager;
}
- (void)afPostRequestWithUrlString:(NSString *)urlString parms:(NSDictionary *)dic finishedBlock:(DownloadFinishedBlock)finished failedBlock:(DownloadFailedBlock)failed
{
 
    if ( _finishedBlock!=finished) {
        _finishedBlock = nil;
        _finishedBlock = finished;
    }
    if (_failedBlock!=failed) {
        _failedBlock = nil;
        _failedBlock = failed;
    }
    _manager = [AFHTTPRequestOperationManager manager];
    _manager.requestSerializer.timeoutInterval=15;
    
    [_manager.requestSerializer setValue:@"x-requested-with" forHTTPHeaderField:@"XMLHttpRequest"];
    [_manager.requestSerializer setValue:@"*/*" forHTTPHeaderField:@"Accept"];
    [_manager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [_manager.requestSerializer setValue:@"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.116 Safari/537.36" forHTTPHeaderField:@"User-Agent"];
    
    _manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    _manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    //Content-Type 要写成与服务器相匹配的类型,一开始可以不写，error信息中会提示我们Content-Type要写成什么
    _manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"text/xml",@"application/json", nil];
    Reachability*reachability=[Reachability reachabilityForInternetConnection];
    
    if([reachability currentReachabilityStatus]==NotReachable){
        NSLog(@"网络不给力");
        if([SaveCachesTool fileExiste:dic[@"xmlmsg"]]){
            NSDictionary*dict=[SaveCachesTool receiveCachesData:dic[@"xmlmsg"]];
            _finishedBlock(dict);
            return;
        }
       
    }


    //实现基本的post请求,函数的参数:为请求地址，和带有post请求参数的字典
 
    [_manager POST:urlString parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
                 XMLDictionaryParser*parse=[XMLDictionaryParser sharedInstance];
                 NSDictionary*dict=[parse dictionaryWithString:operation.responseString];//

        BOOL ret=[SaveCachesTool saveCachesPath:dic[@"xmlmsg"] andcachesData:dict];
        NSLog(@"%ld",(long)ret);

                        _finishedBlock(dict);
                 
             } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             
                 _failedBlock(error.localizedDescription);
                 
             }];
    
}
-(void)cancelRequest
{
    [_manager.operationQueue cancelAllOperations];
}
-(void)systemReceiveImageUrl:(NSString *)url finishedBlock:(DownloadFinishedBlock)finishedBlock andfailedBlico:(DownloadFailedBlock)failedBlock
{
    if (_finishedBlock) {
        //清除上一次的block
        _finishedBlock = nil;
    }
    _finishedBlock = finishedBlock;
    if (_failedBlock) {
        _failedBlock = nil;
    }
    _failedBlock = failedBlock;
    NSURLRequest*request=[NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    _connection=[[NSURLConnection alloc]initWithRequest:request delegate:self];
    
    [_connection start];






}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    //如果data没初始化，则执行初始化操作
    if (!dataArray) {
        dataArray  =[[NSMutableData alloc] init];
    }
    [dataArray setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [dataArray appendData:data];
  //  NSLog(@"%@",data);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    NSString*str=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSError*err=nil;
    BOOL der=  [[NSFileManager defaultManager]createDirectoryAtPath:[str stringByAppendingPathComponent:@"me/laber"] withIntermediateDirectories:YES attributes:nil error:&err];
    
    NSString*path=[str stringByAppendingPathComponent:@"me/laber/11.mp4"];
    BOOL ret=  [dataArray writeToFile:path atomically:YES];
  //  NSLog(@"%@  %ld  %ld",path,(long)ret,(long)der);
    if (_finishedBlock) {
        _finishedBlock(dataArray);
    }
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    if (_failedBlock) {
        _failedBlock(error.localizedDescription);
    }
}
-(void)requestDownDataUrl:(NSString*)url andfileName:(NSString*)name andfileType:(NSString*)type andfinishedBlock:(DownloadFinishedBlock)finishedBlock andfailed:(DownloadFailedBlock)failedBlock
{
    if ( _finishedBlock!=finishedBlock) {
        _finishedBlock = nil;
        _finishedBlock = finishedBlock;
    }
    if (_failedBlock!=failedBlock) {
        _failedBlock = nil;
        _failedBlock = failedBlock;
    }
    NSString*str=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
 
    NSString*pathstr=[NSString stringWithFormat:@"file/laber/%@.%@",[url MD5Hash],type];
    NSString*path=[str stringByAppendingPathComponent:pathstr];
    
    if([[NSFileManager defaultManager]fileExistsAtPath:path]){
    
        _finishedBlock(path);
        return;
    
    }
    
    
    
    //@"http://static.tripbe.com/videofiles/20121214/9533522808.f4v.mp4"
    NSMutableURLRequest *request = [NSMutableURLRequest  requestWithURL:[NSURL URLWithString:url]];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];

    
  //  NSString *range = [NSString stringWithFormat:@"Bytes=%d-",20000000];
  //  [request setValue:range forHTTPHeaderField:@"Range"];
    [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {

      NSLog(@"%ld   %ld    %ld",(long)bytesRead,(long)totalBytesRead,(long)totalBytesExpectedToRead);
    }];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        UIImageWriteToSavedPhotosAlbum([UIImage imageWithData:responseObject], nil, @selector(tt), nil);
      BOOL ret=  [responseObject writeToFile:path atomically:YES];
        if(ret){
           
            
            _finishedBlock(path);
        }
        else{
            
             _failedBlock(@"下载失败");
        }

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        _failedBlock(error.localizedDescription);
        NSLog(@"%@",error);
    }];
    
    operation.outputStream = [NSOutputStream outputStreamToMemory];
    [operation start];


}
-(void)tt
{
    NSLog(@"已存入相册");


}
+(NSURLResponse*)requestfileResponse:(NSString*)url;
{
    NSURLResponse*response=nil;
    NSError*error=nil;
    NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    
    return response;
}
-(void)dealloc
{

    NSLog(@"数据请求释放了");


}




@end
